<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <a-row>
        <!-- <a-col :span="8" :offset="10">
          <a-input-search
            v-action:search
            style="max-width: 300px; min-width: 150px; float: right"
            v-model="queryParam.search"
            placeholder="请输入课程名字"
            @search="onSearch"
          />
        </a-col> -->
        <div class="row-item-tab clearfix">
          <a-range-picker @change="onSelectDate" />
          <a-button icon="download" @click="onExport">订单导出</a-button>
        </div>
      </a-row>
    </div>
    <s-table ref="table" rowKey="order_no" :loading="isLoading" :columns="columns" :data="loadData" :pageSize="15">
       <span slot="card_icon" slot-scope="text">
        <a title="点击查看原图" :href="text" target="_blank">
          <img width="100%" style="max-width: 200px" :src="text" alt="横幅图片" />
        </a>
      </span>
      <div slot="opening_time" slot-scope="text, item">
        <a-tooltip placement="right" arrow-point-at-center>
          <template slot="title">
            {{text}}
          </template>
          <div class="opening_time">{{text}}</div>
        </a-tooltip>
      </div>
      <div slot="limite" slot-scope="text, item">
          <span v-if="item.type == 1">{{text}}次</span>
          <span v-else>不限</span>
      </div>
      <div slot="effective" slot-scope="text, item">
          <span>{{text}}天</span>
      </div>
      <div slot="course_detail" slot-scope="text, item">
        <a-tooltip placement="right" arrow-point-at-center>
          <template slot="title">
            {{text}}
          </template>
          <div class="course_detail">{{text}}</div>
        </a-tooltip>
      </div>
      <div slot="remaining_times" slot-scope="text, item">
          <span v-if="item.type == 1">{{text}}次</span>
          <span v-else>不限</span>
      </div>
    </s-table>
  </a-card>
</template>

<script>
import * as Api from '@/api/membercard/index'
import { STable } from '@/components'
import ExcelJS from 'exceljs'
import * as FileSaver from 'file-saver'

export default {
  name: 'CardOrder',
  components: {
    STable,
  },
  data() {
    return {
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        {
          title: '订单号',
          dataIndex: 'order_no',
          align: 'center'
        },
        {
          title: '会员卡icon',
          dataIndex: 'image.preview_url',
          scopedSlots: { customRender: 'card_icon' },
          align: 'center'
        },
        {
          title: '会员卡名称',
          dataIndex: 'card_name',
          align: 'center'
        },
        {
          title: '有效使用次数',
          dataIndex: 'limite',
          scopedSlots: { customRender: 'limite' },
          align: 'center'
        },
        {
          title: '有效期',
          dataIndex: 'effective',
          scopedSlots: { customRender: 'effective' },
          align: 'center'
        },
        {
          title: '用户ID',
          dataIndex: 'user_id',
          align: 'center'
        },
        {
          title: '用户名',
          dataIndex: 'user.nick_name',
          align: 'center'
        },
        {
          title: '剩余有效天数',
          dataIndex: 'remaining_day',
          align: 'center'
        },
        {
          title: '剩余有效次数',
          dataIndex: 'remaining_times',
          scopedSlots: { customRender: 'remaining_times' },
          align: 'center'
        },
        {
          title: '价格',
          dataIndex: 'price',
          align: 'center'
        },
        {
          title: '购买时间',
          dataIndex: 'pay_time_str',
          align: 'center'
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (param) => {
        return Api.orderList({ ...param, ...this.queryParam })
          .then(response => {
            console.log(response)
            return response.data
          })
      },
      // 选择的导出日期
      exportDate: [],
    }
  },
  created() {},
  methods: {
    /**
     * 新增记录
     */
    handleAdd() {
      this.$refs.AddForm.add()
    },

    /**
     * 编辑记录
     */
    handleEdit(item) {
      this.$refs.EditForm.edit(item)
    },

    /**
     * 删除记录
     */
    handleDelete(item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk() {
          
        },
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.$refs.table.refresh(bool)
    },

    /**
     * 检索查询
     */
    onSearch() {
      this.handleRefresh(true)
    },

    // 导出订单，默认导出当前页数据
    async onExport() {
      const workbook = new ExcelJS.Workbook()
      const sheet = workbook.addWorksheet('会员卡订单')
      sheet.columns = [
        { header: '订单号', key: 'order_no', width: 32 },
        { header: '微信交易号', key: 'transaction_id', width: 32 },
        { header: '会员卡名称', key: 'card_name', width: 12, outlineLevel: 1 },
        { header: '有效使用次数', key: 'limite', width: 12, outlineLevel: 1 },
        { header: '有效期', key: 'effective', width: 12, outlineLevel: 1 },
        { header: '用户ID', key: 'user_id', width: 12, outlineLevel: 1 },
        { header: '用户昵称', key: 'nick_name', width: 10, outlineLevel: 1 },
        { header: '用户姓名', key: 'real_name', width: 10, outlineLevel: 1 },
        { header: '价格', key: 'price', width: 10, outlineLevel: 1 },
        { header: '购买时间', key: 'pay_time_str', width: 22, outlineLevel: 1 },
      ]

      let fileName = `最近的会员卡购买记录.xlsx`
      let { data } = await this.loadData()
      // 有选择导出日期，则按导出日期查询后台
      if (this.hasSelectExportDate()) {
        const dateArr = this.exportDate
        fileName = `会员卡购买记录${dateArr[0]}~${dateArr[1]}`
        const result = await Api.orderListFilter({ dateArr })
        data = result.data
      }

      console.log(data)
      for (let i = 0, len = data.length; i < len; i++) {
        const item = data[i]
        const limite = item.type == 0 ? '不限': item.limite

        sheet.addRow({
          order_no: item.order_no,
          transaction_id: item.transaction_id,
          card_name: item.card_name,
          limite,
          effective: item.effective,
          user_id: item.user_id,
          price: item.price,
          nick_name: item.user.nick_name,
          real_name: item.user.real_name,
          pay_time_str: item.pay_time_str,
        })
      }

      const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
      workbook.xlsx
        .writeBuffer()
        .then((buffer) => {
          const blob = new Blob([buffer], { type: EXCEL_TYPE })
          FileSaver.saveAs(blob, fileName)
        })
        .catch((err) => {
          console.log(err)
        })
    },

    hasSelectExportDate() {
      if (this.exportDate?.[0]) {
        return true
      }

      return false
    },

    onSelectDate(date, dateString) {
      this.exportDate = dateString
    },
  },
}
</script>

<style lang="less" scoped>
.opening_time, .course_detail{
  overflow : hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
